package com.corecloud.controller.sys;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.corecloud.entity.SysPermissionEntity;
import com.corecloud.entity.SysPermissionRoleEntity;
import com.corecloud.service.SysPermissionRoleService;
import com.corecloud.service.SysPermissionService;
import com.corecloud.tools.AjaxResultData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.security.Principal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 权限管理相关
 */
@Controller
@RequestMapping("/permission")
public class PermissionController {


	@Autowired
	private SysPermissionService sysPermissionService;
	@Autowired
	private SysPermissionRoleService sysPermissionRoleService;


	/**
	 * 权限列表页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/index")
	public ModelAndView index(Principal principal){
		ModelAndView modelAndView = new ModelAndView("permission/index");
		return modelAndView;
	}

	/**
	 * 权限列表树结构数据
	 * 异步请求,根据上级ID获取对应下级权限数据
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/tree")
	@ResponseBody
	public List<Map> tree(Principal principal,Integer pid){
		//封装页面数据
		QueryWrapper<SysPermissionEntity> qw = new QueryWrapper<>();
		qw.eq("is_valid",1);
		if(!StringUtils.isEmpty(pid)){
			qw.eq("parent_id",pid);
		}
		List<SysPermissionEntity> pl = sysPermissionService.getListByParas(qw);
		Map dataMap = new HashMap();
		List<Map> resultList = new ArrayList<>();
		//拼装树形数据
		if(pl != null && pl.size() > 0){
			for(int i = 0;i<pl.size();i++){
				SysPermissionEntity sp = pl.get(i);
				dataMap = new HashMap();
				dataMap.put("id",sp.getId());
				dataMap.put("name",sp.getName());
				dataMap.put("pid",sp.getParentId() == null ? 0 : sp.getParentId());
				resultList.add(dataMap);
			}
		}
		return resultList;
	}

	/**
	 * 权限列表数据
	 * @return
	 */
	@RequestMapping("/list")
	@ResponseBody
	public List<SysPermissionEntity> list(Integer isValid,String name,Integer pid){
		QueryWrapper<SysPermissionEntity> qw = new QueryWrapper<>();
		if(isValid != null){ qw.eq("is_valid",isValid); }
		if(pid != null){ qw.eq("parent_id",pid); }
		if(!StringUtils.isEmpty(name)){ qw.like("name",name); }
		return sysPermissionService.getListByParas(qw);
	}



	/**
	 * 添加信息页
	 * @param principal 登录用户信息
	 * @param pid 上级权限信息，也用来区分是添加一级菜单还是其他菜单
	 *              一级参数：1；二级参数：2
	 * @return
	 */
	@RequestMapping("/add")
	public ModelAndView add(Principal principal,Integer pid, String grade){
		//查询上级权限信息,根据上级权限添加子级权限信息
		ModelAndView modelAndView = new ModelAndView("permission/add");
		if(!StringUtils.isEmpty(pid) && pid != -99){
			SysPermissionEntity parentPermission = new SysPermissionEntity();
			parentPermission.setId(pid);
			parentPermission = sysPermissionService.getByParas(parentPermission);
			modelAndView.addObject("parentPermission",parentPermission);
		}
		modelAndView.addObject("grade",grade);
		return modelAndView;
	}

	/**
	 * 修改信息页
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/edit")
	public ModelAndView edit(Principal principal,Integer id, String grade){
		ModelAndView modelAndView = new ModelAndView("permission/edit");
		//查询信息,回填页面
		if(!StringUtils.isEmpty(id)){
			SysPermissionEntity permissionEntity = new SysPermissionEntity();
			permissionEntity.setId(id);
			permissionEntity = sysPermissionService.getByParas(permissionEntity);
			modelAndView.addObject("permissionInfo",permissionEntity);
			modelAndView.addObject("grade",grade);
		}
		return modelAndView;
	}


	/**
	 * 保存权限信息-添加与修改
	 * @param principal 登录用户信息
	 * @param info 需要保存的信息主体
	 * @param tag 操作标签
	 * @param grade 操作等级
	 * @return
	 */
	@RequestMapping("/save")
	@ResponseBody
	public AjaxResultData save(Principal principal,SysPermissionEntity info,String tag, String grade){
		if(StringUtils.isEmpty(tag)){ return new AjaxResultData(500,"参数异常,请联系管理员"); }
		if(StringUtils.isEmpty(info.getName())){ return new AjaxResultData(500,"请填写名称"); }
		if(StringUtils.isEmpty(info.getUrl())){ return new AjaxResultData(500,"请填写URL地址"); }

		info.setUrl(info.getUrl().trim());
		info.setName(info.getName().trim());
		try{
			SysPermissionEntity otherPermission = new SysPermissionEntity();
			SysPermissionEntity paras = new SysPermissionEntity();
			paras.setUrl(info.getUrl());
			System.out.println("----------------------------"+grade);
//			如果操作的为一级菜单允许为空
			if (!grade.equals("1")){
				otherPermission = sysPermissionService.getByParas(paras);
			}else {
				otherPermission = null;
			}

			//添加信息,默认类型为菜单,重置ID信息,为数据库自增
			if(tag.equals("add")){
				System.out.println("----------------------------add");
				info.setId(null);
				//前台页面添加默认为菜单类
				if(otherPermission != null){ return new AjaxResultData(500,"URL地址被占用,请查验后再提交"); }
				System.out.println("----------------------------111111111"+info);
				sysPermissionService.saveInfo(info);
			}else{
				//获取需要修改的数据
				paras = new SysPermissionEntity();
				paras.setId(info.getId());
				SysPermissionEntity oldPermission = sysPermissionService.getByParas(paras);
				//重置参数,查询是否名称或地址已被占用（同级权限中）
				if(otherPermission != null && !otherPermission.getId().equals(oldPermission.getId())){
					return new AjaxResultData(500,"URL地址被占用,请查验后再提交");
				}
				oldPermission.setName(info.getName());
				oldPermission.setUrl(info.getUrl());
				oldPermission.setIsValid(info.getIsValid());
				oldPermission.setType(info.getType());
				// 需同步更新相关表数据
				sysPermissionService.editInfo(oldPermission);
				sysPermissionRoleService.updateInfoByPid(oldPermission.getId());
			}
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}


	/**
	 * 删除权限
	 * @param principal 登录用户信息
	 * @return
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public AjaxResultData delete(Principal principal,Integer pid){
		if(StringUtils.isEmpty(pid)){ return new AjaxResultData(500,"参数异常,请联系管理员"); }
		try{
			//查询是否有上级为此权限的数据,如果有则不能删除
			List<SysPermissionEntity> pl = sysPermissionService.getListByParas(new QueryWrapper<SysPermissionEntity>().eq("parent_id",pid));
			if(pl != null && pl.size() > 0){
				return new AjaxResultData(500,"请先删除子级权限");
			}
			sysPermissionService.deleteInfo(pid);
			//同步删除相关数据
			sysPermissionRoleService.deleteInfo(new QueryWrapper<SysPermissionRoleEntity>().eq("pid",pid));
			return new AjaxResultData("操作成功");
		}catch (Exception e){
			return new AjaxResultData(500,"操作失败,请联系管理员");
		}
	}

}
